<template>
  <div>
    <!-- 使用 Flex 布局的容器 -->
    <div class="toolbar-container">
      <!-- 按钮组（左侧，允许换行） -->
      <div class="button-group">
        <el-button type="primary" size="small" @click="addModal"
          >新增</el-button
        >
        <el-button type="success" size="small" @click="downloadTemplate"
          >下载模板</el-button
        >
        <el-upload action="/api/book/importBook" :show-file-list="false">
          <el-button type="danger" size="small">导入Excel</el-button>
        </el-upload>
        <el-upload action="/api/book/importPic" :show-file-list="false">
          <el-button type="warning" size="small">导入封面图</el-button>
        </el-upload>
      </div>

      <!-- 搜索框（右侧，固定宽度） -->
      <div class="search-group">
        <el-input
          placeholder="输入书名/作者"
          v-model="searchQuery"
          clearable
          @keyup.enter.native="handleSearch"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="handleSearch"
          />
        </el-input>
      </div>
    </div>
    <el-table :data="bookList" style="width: 100%" stripe border>
      <el-table-column label="序号" width="80" align="center">
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="bookName"
        label="书名"
        align="center"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        prop="author"
        label="作者"
        align="center"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column prop="press" label="出版社" width="200" align="center">
      </el-table-column>
      <el-table-column
        prop="publishDate"
        label="出版日期"
        width="100"
        align="center"
      >
      </el-table-column>
      <el-table-column prop="price" label="价格" width="100" align="center">
        <template slot-scope="scope">
          <span>￥{{ scope.row.price }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="editModal(scope.row)"
            >编辑</el-button
          >
          <el-button
            type="text"
            size="small"
            @click="handleDelete(scope.row)"
            style="color: #f56c6c"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="margin-top: 10px; text-align: center"
      @current-change="handleCurrentChange"
      :current-page="pagination.currentPage"
      :page-sizes="pagination.pageSizes"
      :page-size="pagination.pageSize"
      :layout="
        isMobile ? 'prev, pager, next' : 'total, prev, pager, next, sizes'
      "
      :small="isMobile"
      :total="pagination.total"
    >
    </el-pagination>
    <!-- 新增书籍对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      :width="isMobile ? '90%' : '50%'"
      top="20px"
      :close-on-click-modal="false"
    >
      <el-form
        :model="newBook"
        label-width="100px"
        :rules="rules"
        ref="bookForm"
      >
        <el-form-item label="ISBN" prop="isbn">
          <el-input v-model="newBook.isbn"></el-input>
        </el-form-item>

        <el-form-item label="书名" prop="bookName">
          <el-input v-model="newBook.bookName"></el-input>
        </el-form-item>

        <el-form-item label="作者" prop="author">
          <el-input v-model="newBook.author"></el-input>
        </el-form-item>

        <el-form-item label="出版社" prop="press">
          <el-input v-model="newBook.press"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model.number="newBook.price">
            <template slot="prepend">￥</template>
          </el-input>
        </el-form-item>
        <el-form-item label="出版时间" prop="publishDate">
          <el-input
            v-model="newBook.publishYear"
            placeholder="请输入年份(YYYY)"
            style="width: 40%"
          >
          </el-input>
          -
          <el-input
            v-model="newBook.publishMonth"
            placeholder="请输入月份(MM)"
            style="width: 40%"
          >
          </el-input>
        </el-form-item>

        <el-form-item label="分类" prop="category">
          <el-select
            v-model="newBook.categoryList"
            multiple
            placeholder="请选择"
          >
            <el-option
              v-for="item in categoryList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="索书号"
          prop="callNumber"
          v-if="title == '新增图书'"
        >
          <el-input v-model="newBook.callNumber"></el-input>
        </el-form-item>
        <el-form-item label="封面图" prop="cover">
          <el-upload
            action="http://localhost:8084/api/book/upload"
            list-type="picture-card"
            :limit="1"
            :on-exceed="handleExceed"
            :on-success="handleSuccess"
            :on-remove="handleRemove"
            :file-list="fileList"
            :before-upload="beforeUpload"
            accept="image/*"
          >
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">
              只能上传一张图片，且不超过1MB
            </div>
          </el-upload>
        </el-form-item>

        <el-form-item label="简介" prop="summary">
          <el-input
            type="textarea"
            v-model="newBook.summary"
            :rows="3"
          ></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "BookList",
  data() {
    return {
      bookList: [],
      searchQuery: "",
      pagination: {
        currentPage: 1,
        pageSizes: [10],
        pageSize: 10,
        total: 0,
      },
      dialogVisible: false,
      title: "",
      fileList: [],
      newBook: {
        isbn: "",
        bookName: "",
        author: "",
        press: "",
        publishYear: "",
        publishMonth: "",
        publishDate: "",
        price: null,
        categoryList: [],
        callNumber: "",
        cover: "",
        description: "",
      },
      rules: {
        isbn: [
          { required: true, message: "请输入ISBN", trigger: "blur" },
          {
            min: 10,
            max: 13,
            message: "长度在 10 到 13 个字符",
            trigger: "blur",
          },
        ],
        bookName: [{ required: true, message: "请输入书名", trigger: "blur" }],
        author: [{ required: true, message: "请输入作者", trigger: "blur" }],
        price: [
          { required: true, message: "请输入价格", trigger: "blur" },
          { type: "number", message: "价格必须为数字值", trigger: "blur" },
        ],
      },
      categoryList: [],
      isMobile: false,
    };
  },
  mounted() {
    this.checkScreenSize();
    window.addEventListener("resize", this.handleResize);
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.handleResize);
  },
  created() {
    this.fetchCategory();
    this.fetchBooks();
  },
  methods: {
    handleResize() {
      this.checkScreenSize();
    },
    checkScreenSize() {
      this.isMobile = window.innerWidth < 768;
    },
    handleImportSuccess2(response) {
      if (response.code == 200) {
        this.$message.success("导入成功");
      } else {
        this.$message.error(response.message);
      }
    },
    handleImportSuccess(response) {
      if (response.code == 200) {
        this.$message.success("导入成功");
        this.fetchBooks();
      } else {
        this.$message.error(response.message);
      }
    },
    //  下载模板
    downloadTemplate() {
      window.location.href = "/图书导入.xlsx";
    },
    cancel() {
      this.dialogVisible = false;
      this.resetForm();
    },
    addModal() {
      this.dialogVisible = true;
      this.title = "新增图书";
    },
    editModal(row) {
      this.dialogVisible = true;
      this.title = "编辑图书";
      console.log(row);
      this.getById(row);
    },
    handleSearchClear() {
      this.searchQuery = "";
      this.fetchBooks();
    },
    async getById(row) {
      const response = await this.$request.get("/api/book/" + row.id);
      if (response.code == 200) {
        this.newBook = response.data;
        this.newBook.publishYear = response.data.publishDate.substring(0, 4);
        this.newBook.publishMonth = response.data.publishDate.substring(5, 7);
        this.newBook.cover = response.data.coverUrl;
        if (this.newBook.cover) {
          var name =
            this.newBook.cover.split("/")[
              this.newBook.cover.split("/").length - 1
            ];
          // var url = "http://localhost:8084" + this.newBook.cover;
          this.fileList = [
            {
              name: name,
              url: this.newBook.cover,
            },
          ];
        }
      }
    },
    async fetchCategory() {
      const params = {
        search: "",
        curPage: 1,
        pageSize: 100,
      };
      const response = await this.$request.get("/api/category", {
        params: params,
      });
      console.log("fetchCategory", response);
      if (response.code == 200) {
        this.categoryList = response.data.records;
      }
    },
    async fetchBooks() {
      const params = {
        category: 0,
        search: this.searchQuery,
        curPage: this.pagination.currentPage,
        pageSize: this.pagination.pageSize,
      };
      console.log(params);
      const response = await this.$request.get("/api/book", {
        params: params,
      });
      if (response.code == 200) {
        this.bookList = response.data.records;
        this.pagination.total = response.data.total;
      }
    },
    handleSearch() {
      this.pagination.currentPage = 1;
      this.fetchBooks();
    },
    handleCurrentChange(page) {
      this.pagination.currentPage = page;
      this.fetchBooks();
    },
    async handleDelete(row) {
      try {
        await this.$confirm(`确定要删除《${row.bookName}》这本书吗？`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });

        // 用户确认后执行删除
        const response = await this.$request.delete(
          `/api/book/${row.id}/${row.isbn}`
        );

        if (response.code === 200) {
          this.$message.success("删除成功");
          this.fetchBooks();
        } else {
          this.$message.error(response.message);
        }
      } catch (error) {
        // 用户点击取消时 error === 'cancel'
        if (error !== "cancel") {
          this.$message.error(`删除失败: ${error.message || "未知错误"}`);
        } else {
          this.$message.error("取消删除");
        }
      }
    },

    // 文件超出数量限制时的钩子
    handleExceed() {
      this.$message.warning(`只能上传一张图片，请先删除当前图片`);
    },
    // 文件移除时的钩子
    handleRemove(file, fileList) {
      this.fileList = fileList;
      this.$request.post("/api/book/removeCover?filename=" + file.name);
    },

    handleSuccess(response, file, fileList) {
      console.log("上传成功..");
      this.fileList = fileList;
      console.log(fileList);
      this.newBook.cover = response.data;
    },
    beforeUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt1MB = file.size / 1024 / 1024 < 1;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG/PNG 格式!");
      }
      if (!isLt1MB) {
        this.$message.error("上传头像图片大小不能超过 1MB!");
      }
      return isJPG && isLt1MB;
    },
    submitForm() {
      this.$refs.bookForm.validate((valid) => {
        if (valid) {
          this.sumbit();
        } else {
          console.log("表单验证失败");
          return false;
        }
      });
    },
    async sumbit() {
      if (this.newBook.publishMonth && this.newBook.publishYear) {
        this.newBook.publishDate =
          this.newBook.publishYear + "-" + this.newBook.publishMonth;
      }
      console.log(this.newBook);
      this.newBook.coverUrl = this.newBook.cover;
      if (this.title == "新增图书") {
        const response = await this.$request.post("/api/book", this.newBook);
        if (response.code == 200) {
          this.fetchBooks();
          this.$message.success("添加成功!");
          this.dialogVisible = false;
          this.resetForm();
        }
      } else if (this.title == "编辑图书") {
        const response = await this.$request.put("/api/book", this.newBook);
        if (response.code == 200) {
          this.fetchBooks();
          this.$message.success("修改成功!");
          this.dialogVisible = false;
          this.resetForm();
        }
      }
    },
    resetForm() {
      this.newBook = {
        isbn: "",
        bookName: "",
        author: "",
        press: "",
        publishYear: "",
        publishMonth: "",
        publishDate: "",
        price: null,
        categoryList: [],
        callNumber: "",
        cover: "",
        description: "",
      };
      this.fileList = [];
    },
  },
};
</script>

<style scoped>
/* 主容器：Flex 布局，允许换行 */
.toolbar-container {
  display: flex;
  flex-wrap: wrap; /* 允许内容换行 */
  gap: 10px; /* 元素间距 */
  align-items: center; /* 垂直居中 */
  margin-bottom: 10px;
}

/* 按钮组：自动换行 */
.button-group {
  display: flex;
  flex-wrap: wrap; /* 允许按钮换行 */
  gap: 10px; /* 按钮间距 */
  flex: 1; /* 占据剩余空间 */
}

/* 搜索框：固定宽度，右对齐 */
.search-group {
  min-width: 250px; /* 防止搜索框过窄 */
  flex: 0 0 auto; /* 不伸缩、不收缩 */
}

/* 窄屏适配：强制搜索框换行 */
@media (max-width: 768px) {
  .search-group {
    width: 100%; /* 占满整行 */
  }
}
/* 默认样式（桌面端） */
.el-form-item .el-input {
  width: 100%; /* 默认占满父容器 */
}

/* 窄屏适配（移动端） */
@media (max-width: 768px) {
  /* 缩小输入框宽度 */
  .el-form-item .el-input {
    width: 80%;
  }

  /* 调整出版时间的两个输入框布局 */
  .el-form-item [prop="publishDate"] .el-input {
    width: 30% !important; /* 覆盖行内样式 */
  }

  /* 分类选择器占满宽度 */
  .el-form-item [prop="category"] .el-select {
    width: 100%;
  }
}
/* 清除所有按钮的 margin */
.button-group .el-button {
  margin-left: 0 !important;
  margin-right: 0 !important;
}

/* 确保 el-upload 内部的按钮也没有 margin */
.button-group .el-upload .el-button {
  margin-left: 0 !important;
  margin-right: 0 !important;
}
</style>